import { getDefaultOptions } from "~/config"

/** 该js文件会被注入到网页中 */
const postMessageId = '__web_fake'
const noscrollClassName = '__web-fake-noscroll'
/** `front` 对应 iframe 页面， `end` 对应当前访问的真实页面 */
const defaultView: 'front' | 'end' = 'front'
const frameDomId = '__WEB_FAKE__'
let config: TDefaultOptions | null = null
const cssId = '__WEB_FAKE_CSS'

function setIframeCss() {

  if (document.getElementById(cssId)) return

  const style = document.createElement('style')
  style.id = cssId
  style.innerHTML = `.__web-fake-css {
    position:fixed;
    top:0;
    left:0;
    z-index:99999;
    background:#fff;
    height:100vh;
    width:100vw;
  }
  .__web-fake-use-off {
    pointer-events:none;
  }
  .${noscrollClassName} {
    overflow: hidden;
  }
  html {visibility: hidden;}
  body > *:not(.__web-fake-css) {filter:grayscale(var(--web-fake-grayscale,0.9));}
  `
  document.documentElement.appendChild(style)
}

function removeIframeCss() {
  const style = document.getElementById(cssId)
  if (style) {
    style.parentElement?.removeChild(style)
  }
}

/** 切换页面进行操作 */
function togglePointerEventsHandler() {
  const iframe = document.getElementById(frameDomId)!
  const offClassName = '__web-fake-use-off'
  iframe.classList.toggle(offClassName)
  document.documentElement.classList.toggle(noscrollClassName)
}

async function setIframe() {
  const dom = document.getElementById(frameDomId)
  if (!config?.globalEnable || config?.domainBlockList.includes(location.hostname)) {
    if (dom) {
      const cssDom = document.getElementById(cssId)
      if (cssDom) cssDom.parentElement?.removeChild(cssDom)

      dom.parentElement?.removeChild(dom)
      document.documentElement.style.visibility = 'visible'
      document.documentElement.classList.remove(noscrollClassName)
    }
    return
  }

  setIframeCss()
  if (dom) {
    dom.style.opacity = String(config!.opacity / 100)
    dom.style.display = 'block'
  } else {
    const iframe = document.createElement('iframe')
    iframe.id = frameDomId
    iframe.setAttribute('frameborder', 'no')
    iframe.setAttribute('border', '0')
    iframe.classList.add('__web-fake-css')
    iframe.style.opacity = String(config!.opacity / 100)
    iframe.style.display = 'block'
    iframe.src = location.protocol === 'https:' ? config!.linkHttps : config!.linkHttp
    document.body.appendChild(iframe)
    document.documentElement.style.visibility = 'visible'
  }
}

function toggleIframe() {
  const dom = document.getElementById(frameDomId)
  if (dom) {
    if (dom.style.display !== 'block') {
      dom.style.display = 'block'
      document.body.style.setProperty('--web-fake-grayscale', '0.9')
      document.documentElement.classList.add(noscrollClassName)
      setIframeCss()
    } else {
      dom.style.display = 'none'
      document.body.style.setProperty('--web-fake-grayscale', '0')
      document.documentElement.classList.remove(noscrollClassName)
      removeIframeCss()
    }
  }
}

chrome.storage.sync.get().then((items) => {
  config = Object.assign(getDefaultOptions(), items)
  if (window === top && config.globalEnable && config.domainBlockList.indexOf(location.hostname) === -1) {
    setIframeCss()
  }
})

if (window === top) {
  document.addEventListener('DOMContentLoaded', () => {
    if (config && (config.globalEnable === false || config.domainBlockList.indexOf(location.hostname) > -1)) return

    document.documentElement.classList.toggle(noscrollClassName)
    document.documentElement.style.visibility = 'hidden'
  })

  window.addEventListener('message', (e) => {
    if (config?.linkHttps.startsWith(e.origin) && typeof e.data === 'object' && e.data.postMessageId === postMessageId) {
      switch (e.data.type) {
        // 更新浏览器标题
        case 'title':
          document.title = e.data.title
          break
        default:
      }
    }
  })
} else {
  document.addEventListener('DOMContentLoaded', () => {
    top?.window.postMessage({ postMessageId, type: 'title', title: document.title }, '*')
  })
}

chrome.runtime.onMessage.addListener(async (res, sendRes) => {
  if (typeof res === 'object') {
    switch (res.type) {
      case 'config':
        config = res.data
        if (window === top) await setIframe()
        break
      case 'switch-page':
        if (window === top) togglePointerEventsHandler()
        break
      case 'toggle-mask':
        toggleIframe()
        break
      default:
    }
  }
})
